<template>
  <div class="goods-item">
    <van-image lazy-load width="140" height="140" fit="contain" :src="detail.pic" @click="$router.push({path: '/goodsDetail', query: {id: detail.id}})">
      <template v-slot:error>
        <van-image src='imgs/error.png'/>
      </template>
    </van-image>
    <div class="van-multi-ellipsis--l2 title" @click="$router.push({path: '/goodsDetail', query: {id: detail.id}})">
      {{detail.name}}
    </div>
    <van-cell-group :border="false">
      <van-cell class="info">
        <div slot="title">¥{{detail.price | fentoyuan}}</div>
        <div slot="default" @click="addCart">
          <van-image src="imgs/cart.png"/>
        </div>
      </van-cell>
    </van-cell-group>
  </div>
</template>

<script>
import { mapState } from 'vuex'

import userApi from '@/api/userApi'
import config from '@/config/config'
import constants from '@/config/constants'

export default {
  name: 'goodsItem',
  props: ['detail'],
  data () {
    return {

    }
  },
  computed: {
    ...mapState(['user','cartList'])
  },
  methods: {
    /* 添加购物车 */
    async addCart () {
      if(this.user){
        const result = await userApi.addCart({
          goodsId: this.detail.id,
          goodsNum: 1,
          memberId: this.user.id
        });
        if(result.code == constants.SUCCESS){
          this.$store.commit(constants.STORE.UPDATE_CART_LIST);
          this.$toast.success('添加成功');
        }
      }else{
        this.$dialog.confirm({
          title: '',
          message: '还未登录，去登录?'
        })
        .then(() => {
          this.$router.push('/login');
        })
      }
    }
  }
}
</script>

<style lang="scss">
</style>
